<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Application</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <!-- 添加jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="name" placeholder="Your name">
<input type="text" id="message" placeholder="Type your message">
<button id="sendButton">Send</button>
<div id="messages"></div>

<script>
    var stompClient = null;

    $(document).ready(function() {
        connect();
        $('#sendButton').click(sendMessage);
    });

    function connect() {
        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/messages', function (message) {
                showMessage(JSON.parse(message.body));
            });
        });
    }

    function sendMessage() {
        var name = $('#name').val();
        var message = $('#message').val();
        var chatMessage = {
            sender: name,
            content: message,
            type: 'CHAT'
        };
        stompClient.send("/app/chat", {}, JSON.stringify(chatMessage));
    }

    function showMessage(message) {
        $('#messages').append('<p>' + message.sender + ": " + message.content + '</p>');
    }
</script>
</body>
</html>
